#!/bin/bash

# ===========================================
# SQL兼容性检查工具平台 - 部署脚本
# ===========================================

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 显示使用帮助
show_usage() {
    echo "用法: $0 {dev|test|sit|odev|oprod|prd}"
    echo ""
    echo "环境说明:"
    echo "  dev    开发环境 (168.61.74.34)"
    echo "  test   测试环境 (168.61.74.34)"
    echo "  sit    SIT环境 (168.61.74.34)"
    echo "  odev   运维开发环境 (115.159.214.105)"
    echo "  oprod   运维生产环境 (115.159.214.105)"
    echo "  prd    生产环境 (168.61.74.34)"
    echo ""
    echo "示例:"
    echo "  $0 dev    # 部署到开发环境"
    echo "  $0 prd    # 部署到生产环境"
}

# 1. 本地打包
build_project() {
    print_info "开始本地打包..."
    
    mvn clean package -Dmaven.test.skip=true -DskipTests=true
    if [ $? -ne 0 ]; then
        print_error "mvn package 失败，终止部署"
        exit 1
    fi
    
    print_success "本地打包完成"
}

# 获取环境参数
get_environment() {
    local env_arg=$1
    if [ -z "$env_arg" ]; then
        print_error "请指定部署环境"
        show_usage
        exit 1
    fi

    # 根据环境选择服务器配置
    case $env_arg in
        dev|sit|prd|prod)
            # 服务器一配置
            PASSWORD="Qinxiao#12345"
            REMOTE_USER="appadmin"
            REMOTE_HOST="168.61.74.34"
            REMOTE_DIR="/home/appadmin/app/sqlcheck"
            print_info "使用服务器一部署环境: $env_arg ($REMOTE_HOST)"
            ;;
        odev|oprod)
            # 服务器二配置
            PASSWORD="Sunny1234"
            REMOTE_USER="appadmin"
            REMOTE_HOST="115.159.214.105"
            REMOTE_DIR="/home/appadmin/app/sqlcheck"
            print_info "使用服务器二部署环境: $env_arg ($REMOTE_HOST)"
            ;;
        test)
            # 显式匹配test已包含于第一分支，此处冗余保护
            PASSWORD="Qinxiao#12345"
            REMOTE_USER="appadmin"
            REMOTE_HOST="168.61.74.34"
            REMOTE_DIR="/home/appadmin/app/sqlcheck"
            print_info "使用服务器一部署环境: $env_arg ($REMOTE_HOST)"
            ;;
        *)
            print_error "不支持的环境: $env_arg"
            show_usage
            exit 1
            ;;
    esac
}

# 查找最新zip包
find_zip_package() {
    ZIP_FILE=$(ls -t target/sqlcheck-backend-*.zip 2>/dev/null | head -n 1)
    if [ -z "$ZIP_FILE" ]; then
        print_error "未找到zip包，请先执行 mvn clean package"
        exit 1
    fi
    
    print_info "找到部署包: $ZIP_FILE"
    ZIP_BASENAME=$(basename "$ZIP_FILE")
}

# 上传zip包到服务器
upload_package() {
    print_info "正在上传zip包到服务器..."
    
    # 创建远程目录
    sshpass -p "$PASSWORD" ssh "$REMOTE_USER@$REMOTE_HOST" "mkdir -p $REMOTE_DIR"
    
    # 上传文件
    sshpass -p "$PASSWORD" scp "$ZIP_FILE" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/"
    if [ $? -ne 0 ]; then
        print_error "上传zip包失败"
        exit 1
    fi
    
    print_success "上传完成"
}

# 远程部署
remote_deploy() {
    local env_arg=$1
    
    print_info "开始远程部署..."
    
    sshpass -p "$PASSWORD" ssh "$REMOTE_USER@$REMOTE_HOST" << EOF
cd $REMOTE_DIR

# 停止服务
if [ -f "bin/app.sh" ]; then
    ./bin/app.sh stop || true
elif [ -f "bin/stop.sh" ]; then
    ./bin/stop.sh || true
fi

# 清理旧文件
rm -f *.jar
rm -rf lib/
rm -rf config/
rm -rf bin/
rm -rf db/
rm -rf docs/

# 解压新包
unzip -o "$ZIP_BASENAME"

# 设置执行权限
chmod +x bin/*.sh

# 启动服务
./bin/app.sh start $env_arg

# 检查服务状态
sleep 5
if [ -f "bin/app.sh" ]; then
    ./bin/app.sh status
fi
EOF

    if [ $? -ne 0 ]; then
        print_error "远程部署失败"
        exit 1
    fi
    
    print_success "远程部署完成"
}

# 健康检查
health_check() {
    local env_arg=$1
    local port="8094"
    local health_port="18094"
    
    print_info "执行健康检查..."
    
    # 等待服务启动
    sleep 10
    
    # 检查主服务
    if curl -f -s "http://$REMOTE_HOST:$port/health" > /dev/null; then
        print_success "主服务健康检查通过: http://$REMOTE_HOST:$port/health"
    else
        print_warning "主服务健康检查失败: http://$REMOTE_HOST:$port/health"
    fi
    
    # 检查管理端点
    if curl -f -s "http://$REMOTE_HOST:$health_port/health" > /dev/null; then
        print_success "管理端点健康检查通过: http://$REMOTE_HOST:$health_port/health"
    else
        print_warning "管理端点健康检查失败: http://$REMOTE_HOST:$health_port/health"
    fi
}

# 主函数
main() {
    local env_arg=$1
    
    if [ -z "$env_arg" ]; then
        show_usage
        exit 1
    fi
    
    print_info "开始部署 SQL兼容性检查工具平台"
    print_info "目标环境: $env_arg"
    
    # 1. 本地打包
    build_project
    
    # 2. 获取环境配置
    get_environment $env_arg
    
    # 3. 查找部署包
    find_zip_package
    
    # 4. 上传包
    upload_package
    
    # 5. 远程部署
    remote_deploy $env_arg
    
    # 6. 健康检查
    health_check $env_arg
    
    print_success "部署完成！环境: $env_arg"
    print_info "应用地址: http://$REMOTE_HOST:8094"
    print_info "健康检查: http://$REMOTE_HOST:18094/health"
    print_info "API文档: http://$REMOTE_HOST:8094/swagger-ui.html"
}

# 脚本入口
if [ $# -eq 0 ]; then
    show_usage
    exit 1
fi

main "$@"
